package com.itheima.filter;

import com.itheima.exception.BusinessException;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestUri = request.getRequestURI();

        if(requestUri.contains("login")){
            filterChain.doFilter(request, servletResponse);
            return;
        }

        String token = request.getHeader("token");

        if(token == null){
            response.setStatus(401);
            log.error("token is null");
            return;
        }

        try{
            Claims claims = JwtUtils.parserJwt(token);
            log.info("claims:{}", claims);
        } catch (Exception e){
            response.setStatus(401);
            log.error("令牌解析失败：{}", e.getMessage());
//            throw new BusinessException("未登录，请先登录！");
            return;
        }

        filterChain.doFilter(request, response);

    }
}
